<template>
  <view class="page">
    <!-- 自定义Header -->
    <CustomHeader></CustomHeader>
    
    <!-- 页头 -->
    <view class="page-header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">附件简历</text>
        <view class="header-right">
          <!-- 可以放置更多按钮，暂时留空 -->
        </view>
      </view>
    </view>

    <!-- 附件列表区域 -->
    <view class="attachment-list-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>
      
      <view class="attachment-list" v-else>
        <view 
          class="attachment-item"
          v-for="(item, index) in attachmentList"
          :key="item.id || index"
        >
          <view class="attachment-info" @click="previewFile(item)">
            <image class="attachment-icon" :src="getAttachmentIcon(item.fileType)"></image>
            <view class="attachment-details">
              <text class="attachment-name">{{ item.name }}</text>
              <text class="attachment-size">{{ item.size }}</text>
            </view>
          </view>
          <view class="attachment-actions">
            <view class="delete-btn" @click.stop="deleteAttachment(index)">
              <image class="delete-icon" src="/static/icons/x.png"></image>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="attachmentList.length === 0" class="empty-state">
          <image class="empty-icon" src="/static/icons/candidate/resume_attach.png"></image>
          <text class="empty-text">暂无附件简历</text>
          <text class="empty-hint">点击下方按钮上传简历</text>
        </view>
      </view>
      
      <!-- 上传提示 -->
      <view class="upload-hint">
        <text class="hint-text">最多上传3份附件简历</text>
      </view>
    </view>

    <!-- 底部固定上传按钮 -->
    <view class="bottom-upload-btn" @click="uploadResume">
      <text class="upload-text">上传简历</text>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomHeader from "@/components/CustomHeader.vue";
import { getAttachmentUploadSignApi, addAttachmentApi, getAttachmentsApi, deleteAttachmentApi } from "@/api/user";
import { chooseFile, uploadFile2OSS } from "@/utils/file.js";

// 响应式数据
const attachmentList = ref([]);
const loading = ref(false);

// 页面加载时获取附件列表
onLoad(() => {
  getAttachmentList();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取附件列表
const getAttachmentList = async () => {
  try {
    loading.value = true;
    const response = await getAttachmentsApi();
    console.log('获取附件列表成功:', response);
    
    // 转换数据格式以适配前端显示
    attachmentList.value = response.map(item => ({
      id: item.id,
      name: item.fileName,
      size: formatFileSize(item.fileSizeMb * 1024 * 1024), // 转换MB为字节再格式化
      url: item.fileUrl,
      fileType: item.fileType,
      updateTime: item.updateTime
    }));
    
  } catch (error) {
    console.error('获取附件列表失败:', error);
    uni.showToast({
      title: "获取附件列表失败",
      icon: "none",
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};
    
// 删除附件
const deleteAttachment = (index) => {
  const attachment = attachmentList.value[index];
  if (!attachment || !attachment.id) {
    uni.showToast({
      title: "附件信息错误",
      icon: "none",
      duration: 2000
    });
    return;
  }

  uni.showModal({
    title: "确认删除",
    content: "确定要删除这个附件吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          // 显示加载状态
          uni.showLoading({
            title: "删除中...",
            mask: true
          });

          // 调用删除接口
          await deleteAttachmentApi(attachment.id);
          
          uni.hideLoading();
          uni.showToast({
            title: "删除成功",
            icon: "success",
            duration: 1500
          });
          
          // 重新获取附件列表
          await getAttachmentList();
        } catch (error) {
          uni.hideLoading();
          console.error('删除失败:', error);
          uni.showToast({
            title: error.message || "删除失败，请重试",
            icon: "none",
            duration: 2000
          });
        }
      }
    }
  });
};
    
// 预览文件
const previewFile = (attachment) => {
  console.log('点击预览文件:', attachment);
  
  if (!attachment || !attachment.url) {
    uni.showToast({
      title: "文件链接无效",
      icon: "none",
      duration: 2000
    });
    return;
  }

  const fileType = attachment.fileType.toLowerCase();
  const fileName = attachment.name;

  // 跳转到文件预览页面
  uni.navigateTo({
    url: `/pages/common/filePreview?fileUrl=${encodeURIComponent(attachment.url)}&fileName=${encodeURIComponent(fileName)}&fileType=${fileType}`
  });
};

    
// 上传简历
const uploadResume = async () => {
  // 检查是否已达到最大上传数量
  if (attachmentList.value.length >= 3) {
    uni.showToast({
      title: "最多只能上传3份简历",
      icon: "none",
      duration: 2000
    });
    return;
  }
  
  try {
    // 选择文件 - 直接使用uni.chooseFile API
    const fileData = await chooseDocumentFile();
    
    if (!fileData) {
      return;
    }
    
    // 显示上传进度
    uni.showLoading({ title: "上传中..." });
    
    // 使用原始文件名
    const originalFileName = fileData.name;
    console.log('使用原始文件名:', originalFileName);
    
    // 从原始文件名中提取文件类型
    const fileExtension = originalFileName.split('.').pop();
    const fileType = fileExtension ? fileExtension.toLowerCase() : '';
    console.log('从原始文件名提取的文件类型:', fileType);
    
    // 获取文件信息（不包含文件类型，因为我们已经从原始文件名获取了）
    const fileInfo = await getFileInfo(fileData.path);
    
    // 上传文件到OSS，传递文件扩展名
    const fileUrl = await uploadFile2OSS(
      fileData.path,
      "attachment",
      () => getAttachmentUploadSignApi(fileType)
    );
    
    // 调用保存接口
    const attachmentData = {
      fileName: originalFileName, // 使用用户原始文件名
      fileSizeMb: fileInfo.sizeMb,
      fileType: fileType, // 使用从原始文件名提取的文件类型
      fileUrl: fileUrl
    };
    
    await addAttachmentApi(attachmentData);
    
    uni.hideLoading();
    uni.showToast({
      title: "上传成功",
      icon: "success",
      duration: 1500
    });
    
    // 重新获取附件列表
    await getAttachmentList();
    
  } catch (error) {
    uni.hideLoading();
    console.error('上传失败:', error);
    uni.showToast({
      title: error.message || "上传失败，请重试",
      icon: "none",
      duration: 2000
    });
  }
};
    
// 选择文档文件
const chooseDocumentFile = () => {
  return new Promise((resolve, reject) => {
    uni.chooseFile({
      count: 1,
      type: 'file',
      extension: ['pdf', 'doc', 'docx'],
      success: (res) => {
        console.log('选择文件成功:', res);
        if (res.tempFiles && res.tempFiles.length > 0) {
          const file = res.tempFiles[0];
          // 检查文件大小（限制为10MB）
          if (file.size > 10 * 1024 * 1024) {
            uni.showToast({
              title: "文件大小不能超过10MB",
              icon: "none",
              duration: 2000
            });
            resolve(null);
            return;
          }
          // 返回文件路径和原始文件名
          resolve({
            path: file.path,
            name: file.name || file.path.split('/').pop() // 优先使用file.name，否则从路径提取
          });
        } else {
          resolve(null);
        }
      },
      fail: (error) => {
        console.error('选择文件失败:', error);
        uni.showToast({
          title: "选择文件失败",
          icon: "none",
          duration: 2000
        });
        reject(error);
      }
    });
  });
};
    
// 获取文件信息（仅获取文件大小）
const getFileInfo = async (filePath) => {
  return new Promise((resolve, reject) => {
    uni.getFileInfo({
      filePath: filePath,
      success: (res) => {
        console.log('文件路径:', filePath);
        console.log('文件信息:', res);
        
        // 计算文件大小(MB)
        const fileSizeMb = parseFloat((res.size / (1024 * 1024)).toFixed(2));
        
        const fileInfo = {
          sizeBytes: res.size,
          sizeMb: fileSizeMb
        };
        
        console.log('文件信息（仅大小）:', fileInfo);
        resolve(fileInfo);
      },
      fail: (error) => {
        console.error('获取文件信息失败:', error);
        reject(error);
      }
    });
  });
};
    
// 根据文件类型获取对应的图标
const getAttachmentIcon = (fileType) => {
  const base = '/static/icons/candidate/';
  switch (fileType.toLowerCase()) {
    case 'pdf':
      return base + 'pdf.png';
    case 'doc':
      return base + 'doc.png';
    case 'docx':
      return base + 'docx.png';
    case 'png':
      return base + 'PNG.png';
    case 'jpg':
    case 'jpeg':
      return base + 'jpg.png';
    default:
      return base + 'file.png'; // 未知类型使用默认图标
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 页头样式 */
.page-header {
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  width: 60rpx;
}

/* 附件列表容器 */
.attachment-list-container {
  flex: 1;
  padding: 30rpx;
  padding-bottom: 120rpx; /* 为底部按钮留出空间 */
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

/* 附件项样式 */
.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-info {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
  transition: background-color 0.2s ease;
  padding: 8rpx;
  border-radius: 8rpx;
}

.attachment-info:active {
  background-color: #f5f5f5;
}

.attachment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 24rpx;
}

.attachment-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.attachment-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-size {
  font-size: 24rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.attachment-actions {
  display: flex;
  align-items: center;
}

.delete-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 30rpx;
}

.delete-icon {
  width: 32rpx;
  height: 32rpx;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.3;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 16rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.empty-hint {
  font-size: 28rpx;
  color: #ccc;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 上传提示 */
.upload-hint {
  display: flex;
  justify-content: flex-end;
  padding: 0 30rpx;
}

.hint-text {
  font-size: 24rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 底部上传按钮 */
.bottom-upload-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #00bdb4;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.upload-text {
  font-size: 36rpx;
  color: #ffffff;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
</style>
